package com.sh.data.engine.application.service.authority;

import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.domain.authority.model.domain.MenuDomain;
import com.sh.data.engine.domain.authority.model.domain.RoleDomain;
import com.sh.data.engine.domain.authority.service.MenuService;
import com.sh.data.engine.domain.util.ConvertUtil;
import com.sh.data.engine.repository.dao.authority.entity.MenuEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: mengzheng.mhc
 * @date: 2024/7/24 16:56
 */
@Slf4j
@Service
public class CertificateApplicationService {

    @Autowired
    private MenuService menuService;

    public List<MenuDomain> getMenus(String userId) {
        // 可以访问的菜单id集合（都是子菜单）
        // 普通用户查询该用户下属菜单
        List<RoleDomain.SimpleMenuEntity> menusList = menuService.getMenusId(userId);
        if (CollectionUtils.isEmpty(menusList)) {
            throw new BusinessException("userId为" + userId + "的用户菜单为空");
        }

        List<Long> menusIds = menusList.stream().map(RoleDomain.SimpleMenuEntity::getMenuId).toList();

        // 需要找到所有菜单的父
        Map<Long, MenuEntity> allMenus = menuService.list().stream()
            .collect(Collectors.toMap(MenuEntity::getId, Function.identity()));
        List<MenuDomain> menuDomainList = new ArrayList<>();
        for (Long s : menusIds) {
            MenuEntity byId = allMenus.get(s);
            MenuDomain menuDomain = ConvertUtil.copyProperties(byId, MenuDomain.class);
            if (menuDomain != null) {
                menuDomainList.add(menuDomain);
            }
        }

        // 找父级的父级(如果有的话) 即拼装每个菜单的父菜单id  注:默认3级菜单
        for (MenuDomain menuDomain : menuDomainList) {
            if (!"0".equals(menuDomain.getParentId().toString())) {
                MenuEntity menusById = allMenus.get(menuDomain.getParentId());
                if (menusById != null) {
                    if (!"0".equals(menusById.getParentId().toString())) {
                        menuDomain.setParentId2(menusById.getParentId());
                    }
                }
            }
        }

        return menuDomainList;
    }
}
